//初始化并创建摄像头背景
function init() {
  this.timeDelta = 0;
  this.lastTime = Date.now();
  this.phoneStaticTime = 0;
  this.waitCamera = 1;

  //监听摄像头画面
  const contex = wx.createCameraContext();
  const listener = contex.onCameraFrame((frame) => {
    let now = Date.now();
    this.timeDelta = (now - this.lastTime) / 1000;
    this.lastTime = now;
    this.onFrameUpdate(frame);
  });
  listener.start();

  //监听手机处于静止状态的时长（移动后归零）
  let _this = this;
  wx.onAccelerometerChange(function (e) {
    if (Math.abs(e.x) > 1.1 && Math.abs(e.y) > 1.1) {
      //正在摇晃手机;
      _this.phoneStaticTime = 0;
    } else if (Math.abs(e.x) > 0.07 && Math.abs(e.y) > 0.02) {
      //正在轻微移动手机;
      _this.phoneStaticTime = 0;
    } else {
      //手机没动
    }
  });
}

function onFrameUpdate(frame) {
  if (this.waitCamera > 0){
    this.waitCamera -= this.timeDelta;
    return;
  }
  if (this.onScan) {
    this.phoneStaticTime += this.timeDelta;
    if (this.phoneStaticTime > 3){
      this.phoneStaticTime = 0;
      this.onScan(frame);
    }
  }
}

//开始扫描(每2秒返回一张摄像头图片)
function startScan(callback) {
  this.onScan = (frame) => {
    if (callback) {
      callback(frame);
    }
  };
}

//开始扫描
function stopScan() {
  this.onScan = undefined;
}

//开始上传图片比对callback(success)
function uploadFrame(url, imageBase64, token, callback){
  wx.request({
    url: url,
    data: {
      image: imageBase64
    },
    header: {
      'Authorization': token
    },
    method: 'POST',
    success(res) {
      if (res.data.statusCode == 0) {
        callback(true, res.data.result.target.targetId);
      }else{
        console.log('------success:' + JSON.stringify(res.data));
        callback(false);
      }
    },
    fail(err) {
      console.log('------fail:' + err);
      callback(false);
    }
  })
}

module.exports = {
  init: init,
  onFrameUpdate: onFrameUpdate,
  startScan: startScan,
  stopScan: stopScan,
  uploadFrame: uploadFrame
}